<template>
  <n-button type="primary" @click="save">
    <template #icon>
      <n-icon>
        <Save />
      </n-icon>
    </template>
    {{ t("layout.header.Save") }}
  </n-button>
</template>
<script setup>
import { nextTick } from "vue";
import { Save } from "@vicons/carbon";
import { t } from "@/language";
import { zip } from "@/utils/common/pako";
import { useDrawingStore } from "@/store/modules/drawing";
import {
  DefaultScreenshot,
  useSceneInfoStore,
} from "@/store/modules/sceneInfo";
import { useGlobalConfigStore } from "@/store/modules/globalConfig";
import { useDispatchSignal } from "@/hooks/useSignal";
import { fetchUpload } from "@/http/api/sys";
import { filterSize } from "@/utils/common/file";
import { fetchUpdateScene } from "@/http/api/scenes";
import { Storage } from "@/core/Storage";
import { useRoute } from "vue-router";

import JSZip from "jszip";
// import { unzip, zip } from "@/utils/common/pako";
const id = useRoute().params.id;
const dbStorage = new Storage();

const sceneInfoStore = useSceneInfoStore();
const drawingStore = useDrawingStore();
const globalConfigStore = useGlobalConfigStore();

// 将File转换为base64
function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

function save() {
  if (!sceneInfoStore.data.id) {
    sceneInfoStore.setDataFieldValue(
      "id",
      id ? "sceneInfo_test_save_" + id : "sceneInfo_test_save"
    );
  }

  window.$dialog.warning({
    title: "警告",
    content: "确定保存该场景吗？",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: async () => {
      globalConfigStore.loadingText = "生成场景数据，请稍后";
      globalConfigStore.loading = true;

      // 版本自动 +1
      sceneInfoStore.setDataFieldValue(
        "sceneVersion",
        sceneInfoStore.data.sceneVersion + 1
      );

      let coverPicture = sceneInfoStore.data.coverPicture;
      if (coverPicture && coverPicture !== DefaultScreenshot) {
        const f = await fetch(coverPicture);
        const blob = await f.blob();
        // 将封面图片转换为 base64
        const reader = new FileReader();
        coverPicture = await new Promise((resolve) => {
          reader.onloadend = () => resolve(reader.result);
          reader.readAsDataURL(blob);
        });
        sceneInfoStore.setDataFieldValue("coverPicture", coverPicture);
      }

      await nextTick();

      // 保存项目信息
      const sceneInfo = {
        ...sceneInfoStore.data,
        coverPicture,
        hasDrawing: drawingStore.getIsUploaded ? 1 : 0,
        drawingInfo: !drawingStore.getIsUploaded
          ? undefined
          : {
              imgSrc: drawingStore.getImgSrc,
              markList: zip(drawingStore.getMarkList),
              imgInfo: JSON.stringify(drawingStore.getImgInfo),
            },
      };

      globalConfigStore.loadingText = "场景正在压缩...";

      // 存储所有zip包的key
      const zipKeys = [];
      const packConfig = {
        name: id ? "scene_demo_" + id : "scene_demo",
        layer: 1, //layer越小
        sceneInfo,
        zipUploadFun: async (zipFile) => {
          // 将zip文件转换为base64
          // console.log(zipFile)
          const base64Data = await fileToBase64(zipFile);
          const key = zipFile.name
            ? zipFile.name
            : `scene_test_save_${Date.now()}_${Math.random()
                .toString(36)
                .substr(2, 9)}`;
          await dbStorage.setOtherItem(key, base64Data);
          // 记录zip包的key
          // zipKeys.push(key);
          return key;
        },
        onProgress: (progress) => {
          globalConfigStore.loadingText = progress + "%";
        },
        onComplete: async (data) => {
          const params = {
            ...sceneInfo,
            zip: data.firstUploadResult, // 主场景zip包的key
            // groupZipKeys: zipKeys.filter(key => key !== data.firstUploadResult), // 其他group zip包的keys
            zipSize: filterSize(data.totalSize),
            // totalZipNumber: data.totalZipNumber,
            // savedAt: new Date().toISOString()
          };
          params.drawingInfo = undefined;

          // 保存场景信息到本地存储
          await dbStorage.setOtherItem(
            id ? "sceneInfo_test_save_" + id : "sceneInfo_test_save",
            params
          );
          sceneInfoStore.setData(params);

          globalConfigStore.loadingText = "保存成功！";
          setTimeout(() => {
            globalConfigStore.loading = false;
          }, 500);
        },
      };

      window.viewer.modules.package.pack(packConfig);
    },
  });
}
</script>

<style lang="less" scoped></style>
